package cn.com.twoke.game.server.handler;

import cn.com.twoke.game.common.entity.message.LogoutMessage;
import cn.com.twoke.game.common.entity.message.UpdateOnlineUserMessage;
import cn.com.twoke.game.common.handler.MessageHandler;
import cn.com.twoke.game.common.utils.MessageUtil;
import cn.com.twoke.game.server.cache.OnlineUserCache;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class LogoutMessageHandler implements MessageHandler<LogoutMessage> {

    @Override
    public void handle(Selector selector, SocketChannel channel, LogoutMessage message) throws IOException {
        String username = message.getUsername();
        if (OnlineUserCache.has(username)) {
            OnlineUserCache.remove(username);
            message.setState(true);
            System.out.println(message.getUsername() + "退出登录");
        } else {
            message.setMessage("用户登陆失败！！！");
        }
        MessageUtil.writeMessage(channel, message);
        OnlineUserCache.CACHE.forEach((_username, _channel) -> {
            MessageUtil.writeMessage(_channel, new UpdateOnlineUserMessage(OnlineUserCache.CACHE.keySet().toArray(new String[0])));
        });
    }

}
